package com.sms.sendservice.aspect;
import com.alibaba.nacos.shaded.com.google.common.util.concurrent.RateLimiter;
import com.sms.sendservice.annotation.GuavaRateLimit;
import jakarta.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class GuavaRateLimitAspect {
    // 缓存限流器（key：方法名，value：对应的RateLimiter）
    private final Map<String, RateLimiter> limiterMap = new ConcurrentHashMap<>();

    @Pointcut("@annotation(rateLimit)")
    public void pointcut(GuavaRateLimit rateLimit) {}

    @Resource
    private GuavaManager guavaManager ;

    @Around("pointcut(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, GuavaRateLimit rateLimit) throws Throwable {
        // 获取当前方法的唯一标识（如类名+方法名）
        String methodKey = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        // 初始化限流器（首次调用时创建）
       /* RateLimiter limiter = limiterMap.computeIfAbsent(methodKey,
                k -> RateLimiter.create(rateLimit.qps()));*/

        // 尝试获取令牌（非阻塞）
        if (guavaManager.tryAcquire()) {
            return joinPoint.proceed(); // 执行方法
        } else {
            return "请求过于频繁，请稍后再试"; // 限流提示
        }
    }
}
